<template>
	<div class="addProject business-workAdd">
		<div class="addForm zll-form">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item class="formList" prop="storageOutType" label="出库类型：">
							<el-select clearable class="input_right" v-model="addForm.storageOutType" :disabled="type == 'see'">
								<el-option label="领用" value="1"></el-option>
								<el-option label="报废" value="2"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item class="formList" prop="processName" label="大类：">
							<el-select clearable class="input_right" v-model="addForm.processName"
									   :disabled="type == 'see'" @change="changeItemValue">
								<el-option :label="key" :value="key" v-for="(value,key) in itemMaps"
										   :key="key"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item class="formList" prop="takeUser" label="领用人：">
							<el-input clearable class="input_right" v-model="addForm.takeUser"
									  :disabled="type == 'see'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="formList" prop="data2" label="出库号：">
							<el-input clearable class="input_right" v-model="addForm.storageOutCode"
									  disabled></el-input>
						</el-form-item>
						<el-form-item class="formList" prop="storageOutTime" label="出库日期：">
							<el-date-picker v-model="addForm.storageOutTime" type="date" class="input_right"
											format="yyyy-MM-dd"
											value-format="yyyy-MM-dd"
											:disabled="type == 'see'"
											placeholder="请选择出库日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item class="formList" prop="remark" label="备注：">
							<el-input clearable class="input_right" v-model="addForm.remark"
									  :disabled="type == 'see'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="formList" prop="storageOutStatus" label="状态：">
							<el-select clearable class="input_right" v-model="addForm.storageOutStatus" disabled>
								<el-option label="出库" value="1"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item class="formList" prop="storageOutUser" label="出库人：">
							<el-input clearable class="input_right" v-model="addForm.storageOutUser"
									  disabled></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div v-if="type=='add'">
				<div class="con_p">
					<div class="mine-add">
						<span class="tipss">单次最多10个</span>
						<span @click="addTable()"><i class="el-icon-circle-plus"></i></span>
						<span @click.stop="batchDelete()"><i class="el-icon-remove-outline"></i></span>
					</div>
				</div>
				<div class="tableList">
					<table border="1">
						<tr>
							<th width="40"></th>
							<th>品类</th>
							<th>物料代码</th>
							<th>物料名称</th>
							<th width="150">品牌规格</th>
							<th>计量单位</th>
							<th>出库数量</th>
							<th>批次号</th>
							<th width="60"></th>
						</tr>
						<tr v-if="tableList.length == 0" class="noData">
							<td colspan="10">暂无数据</td>
						</tr>
						<tr v-else class="add_Table" v-for="(item, index) in tableList" :key="index">
							<td width="40">
								<el-checkbox v-model="item.checked"></el-checkbox>
							</td>
							<td>
								<el-select v-model="item.itemId" placeholder="" class="text_center" clearable
										   :disabled="type == 'see'" @change="changeMaterial(item)">
									<el-option :label="ita.name" :value="ita.categoryId"
											   v-for="(ita,index) in materialItems" :key="ita.name"></el-option>
								</el-select>
							</td>
							<td>
								<el-select v-model="item.materialId" placeholder="" class="text_center" clearable
										   :disabled="type == 'see'"  @change="chooseMaterial(item)">
									<el-option :label="ma.materialName" :value="ma.id"
											   v-for="(ma,index) in materials" :key="ma.id"></el-option>
								</el-select>
							</td>
							<td>
								<el-input v-model="item.materialCode" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-input v-model="item.materialGrade" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-input v-model="item.measureUnit" placeholder="" class="text_center" clearable
										  disabled></el-input>
							</td>
							<td>
								<el-input v-model="item.outCount"
										  @input="item.outCount=item.outCount.replace(/[^\d]/g,'')"
										  placeholder="" class="text_center" clearable
										  :disabled="type == 'see'" @change="totalPriceChange(item)"></el-input>
							</td>
							<td>
								<el-input v-model="item.outBatchCode" placeholder="" class="text_center" clearable
										  :disabled="type == 'see'"></el-input>
							</td>
							<td width="60">
								<span class="edit" @click.stop="deleteTable(item,index)">删除</span>
							</td>
						</tr>
					</table>
				</div>
			</div>
			<div v-else>
				<div class="tableList" style="margin-top: 0;">
					<table border="1">
						<tr>
							<th>品类</th>
							<th>物料代码</th>
							<th>物料名称</th>
							<th width="150">品牌规格</th>
							<th>计量单位</th>
							<th>出库数量</th>
							<th>批次号</th>
						</tr>
						<tr class="add_Table" v-for="(materialDetail,index) in materialDetails">
							<td><p>{{ materialDetail.categoryId }}</p></td>
							<td><p>{{ materialDetail.materialCode }}</p></td>
							<td><p>{{ materialDetail.materialName }}</p></td>
							<td><p>{{ materialDetail.formatMaterial }}</p></td>
							<td><p>{{ materialDetail.measureUnitId }}</p></td>
							<td><p>{{ materialDetail.outCount }}</p></td>
							<td><p>{{ materialDetail.outBatchCode }}</p></td>
						</tr>
					</table>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import {getStore} from "@/plugins/localStore";
	import {formatDate} from "@/plugins/formatDate";

	export default {
		props: ['editData', 'type'],
		data() {
			return {
				addForm: {
					id: '',
					storageOutType: '',
					processName: '',
					takeUser: '',
					storageOutCode: '',
					storageOutTime: '',
					remark: '',
					storageOutStatus: '1',
					storageOutUser: '',
				},
				rules: {
					storageOutType: [
						{required: true, message: '请选择出库类型', trigger: 'change'},
					],
					processName: [
						{required: true, message: '请选择大类', trigger: 'change'},
					],
					takeUser: [
						{required: true, message: '请输入领用人', trigger: 'blur'},
					],
					storageOutTime: [
						{required: true, message: '请选择出库日期', trigger: 'change'},
					],
				},
				materialDetails:[],
				tableList: [],
				itemMaps: {},
				materialItems: [],
				materials: [],
				user:{},
				count:0,
			}
		},
		methods: {
			submitForm() {
				let self = this;
				if(self.tableList.length == 0){
					self.$message.warning('请添加出库记录！');
					return;
				}
				self.$refs["addForm"].validate((valid) => {
					if (valid) {
						for (let data of self.tableList) {
							if (!data.materialId) {
								self.$message.warning('请选择物料代码');
								return -1;
							}  else if (!data.outCount) {
								self.$message.warning('请输入出库数量');
								return -1;
							} else if (!data.outBatchCode) {
								self.$message.warning('请输入批次号');
								return -1;
							}
						}
						self.operate();
					} else {
						return false;
					}
				});

			},

			operate() {
				let self = this;
				let param = Object.assign({},this.addForm);
				param.procureStorageOutHisList = this.tableList;
				if (self.count == 0) {
					self.$http({
						url: '/jinl/procureStorageOut/addProcureStorageOut',
						method: "post",
						data: JSON.stringify(param),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							self.$notify({title: '提示', message: "操作成功！", type: 'success'});
							self.count--;
							self.$emit("refreshPage");
							return;
						}
						self.$notify({title: '提示', message: resp.message, type: 'error'});
						self.count--;
					});
					self.count++;
				}
			},

			getProcureStorageOutHisById() {
				let self = this;
				self.materialDetails = []
				self.$http({
					url: '/jinl/procureStorageOut/getProcureStorageOutHisById',
					method: "post",
					params:{id:self.addForm.id}
				}).then(resp => {
					if (resp.success) {
						self.materialDetails = resp.result;
						return;
					}
					self.$notify({title: '提示', message: resp.message, type: 'error'});
				});
			},

			addTable() {
				if (this.tableList.length < 10) {
					this.tableList.push(
						{
							id:'',
							checked:false,
							itemId:'',
							materialId:'',
							materialName:'',
							materialCode:'',
							materialGrade:'',
							measureUnit:'',
							procurePrice:'',
							procureCount:'',
							procureTotalPrice:'',
						},
					);
				} else {
					this.$notify({title: '提示', message: "单次出库最多10个", type: 'warning'});
				}
			},
			batchDelete() {
				let filter = this.tableList.filter((item) => !item.checked);
				if(filter.length == 0){
					this.$message.warning('至少保留一条数据');
					return;
				}
				this.tableList = JSON.parse(JSON.stringify(filter))
			},

			deleteTable(item, index) {//删除table
				if(this.tableList.length == 1){
					this.$message.warning('至少保留一条数据');
					return;
				}
				this.tableList.splice(index, 1);
			},

			getMaterialByGroupBigTypeId() {
				let self = this;
				self.itemMaps = {};
				self.$http({
					url: "/jinl/material/getMaterialByGroupBigTypeId",
					method: "post",
				}).then(resp => {
					if (resp.success) {
						self.itemMaps = resp.result;
						console.log(self.itemMaps)
					}
				});
			},

			changeItemValue() {
				this.tableList = [];
				this.addTable();
				this.materials = [];
				this.materialItems = [];
				if(!this.addForm.processName){
					return;
				}
				let items = this.itemMaps[this.addForm.processName];
				let materials = [];
				for (let m of items) {
					let caId = m.categoryId;
					let existIndex = materials.findIndex((mm) => mm.categoryId == caId);
					if (existIndex < 0) {
						let obj = {name: m.itemAlias, categoryId: caId, children: [m]};
						materials.push(obj);
					} else {
						materials[existIndex].children.push(m);
					}
				}
				this.materials = [];
				this.materialItems = materials;

			},

			changeMaterial(item){
				this.materials = [];
				item.materialId = '';
				item.materialCode = '';
				item.measureUnit = '';
				item.materialName = '';
				let index = this.materialItems.findIndex((mm) =>mm.categoryId == item.itemId);
				if(index > -1){
					this.materials = this.materialItems[index].children;
				}
				console.log(this.materials)
			},

			chooseMaterial(item){
				let index = this.materials.findIndex((mm) =>mm.id == item.materialId);
				console.log(index)
				if(index < 0){
					return;
				}
				item.materialCode = this.materials[index].materialCode;
				item.measureUnit = this.materials[index].measureUnit;
				item.materialGrade = this.materials[index].formatMaterial;
				item.materialName = this.materials[index].materialName;
			},

		},
		watch:{
			editData(val) {
				console.log('======editData=========')
				console.log(val)
				this.user = getStore();
				this.count = 0;
				for (let key in  this.addForm) {
					this.addForm[key] = val[key] || ''
				}
				if (this.type == 'add' ) {
					let self = this;
					self.addForm.storageOutUser = this.user.userName;
					self.$nextTick(() => {
						self.addTable();
					});
				}else{
					this.getProcureStorageOutHisById();
				}
			},
		},

		mounted() {
			this.getMaterialByGroupBigTypeId();
		},
		components: {},
	}
</script>
<style lang="scss" scoped>
	@import "@/style/dialog.scss";

	.dc {
		width: 100px;
		background: #e6a23c;
	}
</style>